var mysqlClient = require('../libs/mysqlClient');
var redisClient = require('../libs/redisClient');
const encryptUtils = require('../utils/encryptUtils');

function Service() {
    //getUserInfo

    this.list = function (params, callback) {
        callback(params['*session']);
    };

    function organizationLogin(params, callback) {
        const {userName, password} = params;
        mysqlClient.getObject('t_organization', {username: userName}, function (data) {
            if (data) {
                if (data.password === encryptUtils.encrypt(password, data.salt)) {
                    redisClient.set(params['*session'].sid, data);
                    callback({result: true, token: params['*session'].sid});
                } else {
                    callback({error: '密码错误'})
                }
            } else {

                callback({error: '该用户不存在'});
            }
        });
    }

    function teacherLogin(params, callback) {
        const {userName, password} = params;
        mysqlClient.getObject('t_teacher', {username: userName}, function (data) {
            if (data) {
                if (data.password === password) {
                    redisClient.set(params['*session'].sid, data);
                    callback({result: true, token: params['*session'].sid});
                } else {
                    callback({error: '密码错误'})
                }
            } else {
                callback({error: '该用户不存在'});
            }
        });
    }

    function userLogin(params, callback) {
        const {userName, password} = params;
        mysqlClient.getObject('t_user', {username: userName}, function (data) {
            if (data) {
                if (data.password === password) {
                    redisClient.set(params['*session'].sid, data);
                    callback({result: true, token: params['*session'].sid});
                } else {
                    callback({error: '密码错误'})
                }
            } else {
                callback({error: '该用户不存在'});
            }
        });
    }

    this.create = function (params, callback) {
        switch (params['type']) {
            case '1':
                organizationLogin(params, callback);
                break;
            case '2':
                teacherLogin(params, callback);
                break;
            case '3':
                userLogin(params, callback);
                break;

        }
        //login
    };
    //logout
    this.delete = function (id, params, callback) {
        redisClient.del(params['*session'].sid);
        callback({result: true});
    }
}

exports.service = Service;